package com.romeo_foxtrot.labs.vaadin;

import java.util.concurrent.atomic.AtomicInteger;

import com.vaadin.ui.Label;

/**
 * fragment is not preserved, in which case use link instead.
 * 
 * TODO need styling and tab-index (Focusable might help)
 * 
 * @author renfeng
 * 
 */
public class NewWindowButton extends Label {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6851837988535628727L;

	private static final AtomicInteger index = new AtomicInteger();

	private final String name;

	public NewWindowButton() {

		super("", Label.CONTENT_XHTML);

		name = "popup" + index.incrementAndGet();

		return;
	}

	public void display(String caption, String url) {

		StringBuilder sb = new StringBuilder("<form name='" + name
				+ "' target='_blank'");
		// StringBuilder sb = new StringBuilder("<form target='_blank'");

		/*
		 * XXX can't preserve fragment
		 */
		int queryStartAt = url.indexOf("?");
		if (queryStartAt == -1) {
			sb.append(" action='" + url + "'>");
		} else {
			sb.append(" action='" + url.substring(0, queryStartAt) + "'>");

			String query = url.substring(queryStartAt + 1);

			String[] params = query.split("&");
			for (String p : params) {
				String[] s = p.split("=");
				sb.append("<input name='" + s[0] + "' value='" + s[1]
						+ "' type='hidden'/>");
			}
		}

		sb.append("<input value='" + caption + "' type='submit'/>");
		sb.append("</form>");
		/*
		 * XXX why not use Link instead?!
		 */
		// sb.append("<a href='javascript:document." + name + ".submit()'>"
		// + caption + "</a>");

		setValue(sb.toString());

		// getWindow().executeJavaScript("document." + name + ".submit()");

		return;
	}
}
